import React, {PropsWithChildren, useCallback, useEffect, useMemo, useState} from 'react'
import {
    Button,
    Card,
    Collapse, DatePicker,
    Descriptions,
    Divider,
    Drawer, DrawerProps,
    Empty,
    Form,
    Modal,
    Pagination,
    Space, Table,
    Typography
} from "antd";
import {
    ConfigureMarketShoppingGuideSalaryPlanResponse,
    getMarketShoppingGuideSalaryPlan
} from "../../apis/MarketShoppingGuideSalaryPlanApi";
import EditMarketShoppingGuideSalaryPlanDrawer, {
    MarketShoppingGuideSalaryPlanRow
} from "../EditMarketShoppingGuideSalaryPlanDrawer";
import {Pageable} from "../../utils/Page";
import {
    findMonthlyMarketGuideSalarySummary,
    findMonthlyMarketShoppingGuideSalaryDocumentGroupByEmployee,
    generateMarketShoppingGuideSalaryDocuments,
    MonthlySalaryGroupByEmployeeItemResponse,
    MonthlySalaryGroupByEmployeeResponse,
    previewMonthlyMarketShoppingGuideSalaryDocuments,
    PreviewMonthlySalaryDocumentsEmployeeSalaryItemResponse,
    PreviewMonthlySalaryDocumentsResponse,
    PreviewMonthlySalaryDocumentsRuleSalaryResponse,
    QueryMarketShoppingGuideSalaryDocumentGroupByMonthResponse
} from "../../apis/MarketShoppingGuideSalaryDocumentApi";
import dayjs from "dayjs";
import {
    getExistedYearMonthOfMarketSaleDocumentsByMarketId
} from "../../apis/MarketSaleDocumentApi";
import LoadableButton from "../LoadableButton";
import ArrayUtils from "@zxy-cn/array-utils";
import {
    MarketShoppingGuideSalaryPlanRuleDetailPreviewResponse,
    previewSalaryPlanRuleDetail
} from "../../apis/MarketShoppingGuideSalaryPlanDetailPreviewApi";
import {
    getCopiedSalaryPlanResultPlan,
    MarketShoppingGuideSalaryPlanResultPlanResponse
} from "../../apis/MarketShoppingGuideSalaryPlanResultApi";
import {GoodsMatcherResultDrawer} from "../GoodsMatcherRuleFormItems";

export interface MarketSalaryTabPanelProps extends PropsWithChildren {
    id: number
}

const MarketSalaryTabPanel: React.FC<MarketSalaryTabPanelProps> = ({id}) => {
    const [configuration, setConfiguration] = useState<ConfigureMarketShoppingGuideSalaryPlanResponse>()
    const [loading, setLoading] = useState(false)
    useEffect(() => {
        setLoading(true)
        getMarketShoppingGuideSalaryPlan(id).then(response => {
            setConfiguration(response.data)
        }).finally(() => {
            setLoading(false)
        })
    }, [id]);
    const [openConfigureMarketShoppingGuideSalaryPlanDrawer, setOpenConfigureMarketShoppingGuideSalaryPlanDrawer] = useState(false)
    const [loadingSalaryDocument, setLoadingSalaryDocument] = useState(false)

    const [pageable, setPageable] = useState(new Pageable())
    const [documents, setDocuments] = useState<QueryMarketShoppingGuideSalaryDocumentGroupByMonthResponse[]>([])


    const [totalElements, setTotalElements] = useState(0)

    const [openGenerateSalaryDocumentDrawer, setOpenGenerateSalaryDocumentDrawer] = useState(false)
    let querySalaryDocuments = useCallback(() => {
        setLoadingSalaryDocument(true)
        findMonthlyMarketGuideSalarySummary(id, pageable).then(response => {
            setDocuments(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoadingSalaryDocument(false)
        })
    }, [id, ...pageable.toDependencyList()]);
    useEffect(() => {
        querySalaryDocuments()
    }, [querySalaryDocuments]);

    return <>
        <Space direction={"vertical"} style={{width: "100%"}}>
            <Card loading={loading} title={"方案"} extra={<Space>
                <Button onClick={() => {
                    setOpenConfigureMarketShoppingGuideSalaryPlanDrawer(true)
                }}>配置</Button>
            </Space>}>

                {configuration ? <><Descriptions>
                    {!!configuration.minimumSalary &&
                        <Descriptions.Item label={"保底工资"}>{configuration.minimumSalary}</Descriptions.Item>}
                </Descriptions>
                    <Space direction={"vertical"}>
                        {configuration.rules.map(rule => {


                            return <MarketShoppingGuideSalaryPlanRow value={rule}/>
                        })}
                    </Space>
                </> : "未配置"}
            </Card>
            <Card loading={loadingSalaryDocument} title={"工资档案"}
                  extra={<>{<Button disabled={!configuration} onClick={() => {
                      setOpenGenerateSalaryDocumentDrawer(true)
                  }}>根据配置生成</Button>}</>}>
                {!loadingSalaryDocument && totalElements === 0 ? <Empty/> : <>

                    <Collapse
                        items={(documents.map(document => ({
                            label: <div style={{display: "flex", justifyContent: "space-between"}}>
                                <div>{`${document.year}年${document.month}月`}</div>
                                <div>总计<Typography.Text strong>{document.totalSalary}</Typography.Text></div>
                            </div>,
                            children: <MonthlyMarketSalaryCollapseContent marketId={id} year={document.year}
                                                                          month={document.month}/>
                        })))}/>
                    <div style={{display: "flex", justifyContent: "center", marginTop: 24}}>
                        <Pagination style={{justifyContent: "center"}} current={pageable.page} pageSize={pageable.size}
                                    total={totalElements}
                                    onChange={(page, size) => {
                                        setPageable(new Pageable(page, size))
                                    }}/>
                    </div>
                </>}

            </Card>
        </Space>
        <EditMarketShoppingGuideSalaryPlanDrawer initialValue={configuration}
                                                 open={openConfigureMarketShoppingGuideSalaryPlanDrawer}
                                                 onClose={function (): void {
                                                     setOpenConfigureMarketShoppingGuideSalaryPlanDrawer(false)
                                                 }} marketId={id}
                                                 onCompleted={function (value: ConfigureMarketShoppingGuideSalaryPlanResponse): void {
                                                     setConfiguration(value)
                                                     setOpenConfigureMarketShoppingGuideSalaryPlanDrawer(false)
                                                 }}/>
        {
            <GenerateMarketGuideSalaryDocumentDrawer open={openGenerateSalaryDocumentDrawer}
                                                     id={id}
                                                     onCompleted={() => {
                                                         setOpenGenerateSalaryDocumentDrawer(false)
                                                         querySalaryDocuments()
                                                     }}
                                                     onClose={() => setOpenGenerateSalaryDocumentDrawer(false)}/>}
    </>
}

export default MarketSalaryTabPanel


export interface GenerateMarketGuideSalaryDocumentDrawerProps extends PropsWithChildren {
    id: number
    open: boolean
    onClose: () => void
    onCompleted: () => void
}

/**
 * 用于生成工资档案
 *
 * 获取所有销量记录存在的月份，用于选择月份，选择月份后，显示工资档案的预览，每个促销员在这个月的工资明细，若点击生成，则在服务器生成此工资档案。
 * @param id 卖场id
 */
const GenerateMarketGuideSalaryDocumentDrawer: React.FC<GenerateMarketGuideSalaryDocumentDrawerProps> = ({
                                                                                                             id,
                                                                                                             open,
                                                                                                             onClose,
                                                                                                             onCompleted
                                                                                                         }) => {
    const [existedYearMonth, setExistedYearMonth] = useState<string[]>([])
    useEffect(() => {
        if (open)
            getExistedYearMonthOfMarketSaleDocumentsByMarketId(id).then(response => {
                setExistedYearMonth(response.data)
            })
    }, [id, open]);

    const [year, setYear] = useState(new Date().getFullYear())
    const [month, setMonth] = useState(new Date().getMonth())

    const existedYearMonthDayjsArray = useMemo(() => {
        return existedYearMonth.map(it => dayjs(it))
    }, [existedYearMonth]);

    const monthHasData = useMemo(() => {
        return existedYearMonthDayjsArray.some(it => it.year() === year && it.month() === month - 1)
    }, [year, month, existedYearMonthDayjsArray]);
    useEffect(() => {
        if (open && monthHasData) {
            previewMonthlyMarketShoppingGuideSalaryDocuments(id, year, month).then(response => {
                setPreviewData(response.data)
            })
        }
    }, [year, month, id, open, monthHasData]);

    const [previewData, setPreviewData] = useState<PreviewMonthlySalaryDocumentsResponse>()
    const [modal, contextHolder] = Modal.useModal();

    const [previewRuleId, setPreviewDetailRuleId] = useState<number>()
    return <>
        {contextHolder}
        <SalaryRuleDetailPreviewDrawer open={!!previewRuleId} ruleId={previewRuleId} year={year} month={month}
                                       onClose={() => {
                                           setPreviewDetailRuleId(undefined)
                                       }}/>
        <Drawer title={"生成工资档案"} open={open} onClose={onClose} width={document.body.clientWidth * 0.618}>
            <Form>
                <Form.Item label={`选择月份`} required>
                    <DatePicker.MonthPicker
                        disabledDate={d => !existedYearMonthDayjsArray.some(i => d.year() === i.year() && d.month() === i.month())}
                        value={dayjs().year(year).month(month - 1)} onChange={value => {
                        setYear(value.year())
                        setMonth(value.month() + 1)
                    }}/>
                </Form.Item>
            </Form>
            {!!previewData && <>{/*    显示工资方案的统计数据,全部规则的,总工资,总销售,各个方案明细下的总销售,总工资*/}
                <Descriptions title={"工资档案生成预览"} extra={<LoadableButton type={"primary"} onClick={async () => {
                    const confirmed = await modal.confirm({
                        title: "生成工资档案将会删除旧的工资档案（如果有），是否继续？",
                    })
                    if (confirmed) {
                        await generateMarketShoppingGuideSalaryDocuments(id, year, month)
                        onCompleted()
                    }
                }}>生成</LoadableButton>}>
                    <Descriptions.Item label={"总销售额"}>{previewData.totalSale}</Descriptions.Item>
                    <Descriptions.Item label={"总工资"}>{previewData.totalSalary}</Descriptions.Item>
                </Descriptions>
                {/*    各个导购的总工资,方案明细下的总工资*/}
                <Divider/>
                <Table<PreviewMonthlySalaryDocumentsRuleSalaryResponse> pagination={{position: ["none"]}} columns={
                    [
                        {title: "规则名称", dataIndex: "name", key: "name"},
                        {title: "产生工资", dataIndex: "salary", key: "salary"},
                        {title: "说明", dataIndex: "note", key: "note"},
                        {
                            title: "",
                            dataIndex: "actions",
                            render: (_, record, index) => {
                                return <>
                                    {<Button type={"link"} onClick={() => {
                                        setPreviewDetailRuleId(record.id)
                                    }}>查看明细</Button>}
                                </>
                            }
                        }
                    ]
                } dataSource={previewData.ruleSalaries}></Table>
                {previewData.employeeSalaries.map(it => <>
                    <Divider/>
                    <Card key={it.id} title={it.name} size={"small"} extra={
                        <>本月工资<Typography.Text strong>{it.totalSalary}</Typography.Text></>}>
                        <Table<PreviewMonthlySalaryDocumentsEmployeeSalaryItemResponse>
                            pagination={{position: ["none"]}}
                            dataSource={it.items}
                            columns={[{
                                title: "工资项",
                                dataIndex: "name"
                            },
                                {
                                    title: "工资数额",
                                    dataIndex: "salary"
                                },
                                {
                                    title: "说明",
                                    dataIndex: "note"
                                }]}/>
                    </Card></>)}

            </>
            }

        </Drawer>
    </>
}

interface MonthlyMarketSalaryCollapseContentProps {
    marketId: number
    year: number
    month: number
}

const MonthlyMarketSalaryCollapseContent: React.FC<MonthlyMarketSalaryCollapseContentProps> = (props) => {
    const [data, setData] = useState<MonthlySalaryGroupByEmployeeResponse[]>([])
    useEffect(() => {
        findMonthlyMarketShoppingGuideSalaryDocumentGroupByEmployee(props.marketId, props.year, props.month).then(response => {
            setData(response.data)
        })
    }, []);
    return <>
        <Collapse items={[{
            key: 1,
            label: "方案",
            children: <MarketShoppingGuideSalaryPlanResultCopiedPlanCollapseContent marketId={props.marketId}
                                                                                    year={props.year}
                                                                                    month={props.month}/>
        }]}/>
        <Divider/>
        {data.map((it, index) => <>
            {index !== 0 && <Divider/>}
            <Card key={it.id} title={it.employee.name} size={"small"} extra={
                <>本月工资<Typography.Text strong>{ArrayUtils.sum(it.items.map(e => e.salary))}</Typography.Text></>}>
                <Table<MonthlySalaryGroupByEmployeeItemResponse>
                    pagination={{position: ["none"]}}
                    dataSource={it.items}
                    rowKey={"id"}
                    columns={[{
                        title: "工资项",
                        dataIndex: "name"
                    },
                        {
                            title: "工资数额",
                            dataIndex: "salary"
                        },
                        {
                            title: "备注",
                            dataIndex: "note"
                        }]}/>
            </Card></>)}
    </>
}

export interface SalaryRuleDetailPreviewDrawerProps extends DrawerProps {
    ruleId?: number
    year: number
    month: number
}

const SalaryRuleDetailPreviewDrawer: React.FC<SalaryRuleDetailPreviewDrawerProps> = (props) => {
    const [data, setData] = useState<MarketShoppingGuideSalaryPlanRuleDetailPreviewResponse[]>([])
    useEffect(() => {
        if (props.ruleId)
            previewSalaryPlanRuleDetail(props.ruleId, props.year, props.month).then(response => {
                setData(response.data)
            })
        else {
            setData([])
        }
    }, [props.ruleId, props.year, props.month]);
    return <>
        <GoodsMatcherResultDrawer data={data} {...props} width={document.body.clientWidth * 0.618}
                                  title={"工资档案明细预览"}/>
    </>
}

export interface MarketShoppingGuideSalaryPlanResultCopiedPlanCollapseContentProps {
    marketId: number
    year: number
    month: number
}

export const MarketShoppingGuideSalaryPlanResultCopiedPlanCollapseContent: React.FC<MarketShoppingGuideSalaryPlanResultCopiedPlanCollapseContentProps> = (props) => {
    const [data, setData] = useState<MarketShoppingGuideSalaryPlanResultPlanResponse>()
    useEffect(() => {
        getCopiedSalaryPlanResultPlan(props.marketId, props.year, props.month).then(response => {
            setData(response.data)
        })
    }, [props.year, props.month, props.marketId]);
    return <>
        {!!data?.minimumSalary && <Descriptions>
            <Descriptions.Item label={"保底工资"}>{data?.minimumSalary}</Descriptions.Item>
        </Descriptions>}
        {data?.rules?.map((rule, index) => {
            return <MarketShoppingGuideSalaryPlanRow value={{...rule, id: index}}/>
        })}
    </>
}